/**
 *
 * @author John Creecy
 */

package battlebarnserver;

import battlebarnapplet.ClientStart;
import java.io.IOException;
import java.net.*;
import java.util.logging.Level;
import java.util.logging.Logger;

public class GameListener implements Runnable {

	private DatagramSocket serverSocket;

	public GameListener() {
		try {
			serverSocket = new DatagramSocket(ClientStart.serverPort);
		} catch (SocketException ex) {
			Logger.getLogger(GameListener.class.getName()).log(Level.SEVERE, null, ex);
		}
	}

	public void run() {
		socketMonitor();
	}

	public void socketMonitor() {
		Long timeStamp;
		while (true) {
			byte[] receiveData = new byte[1024];
			timeStamp = (long) (System.currentTimeMillis());
			try {
				DatagramPacket receivePacket = new DatagramPacket(receiveData, receiveData.length);
				serverSocket.receive(receivePacket);
				String packetData = new String(receivePacket.getData());
				InetAddress sourceIp = receivePacket.getAddress();
				String sourceIpString = sourceIp.toString();
				String ipAddress = sourceIpString.substring(1, sourceIp.toString().length());

				if(BattleBarn.clientList.containsKey(ipAddress)) {
					BattleBarn.clientList.put(ipAddress, timeStamp);
				} else {
					Runnable runnable = new ClientSignOnThread(ipAddress);
					BattleBarn.addClientSignOnTask(runnable);
					BattleBarn.clientList.put(ipAddress, timeStamp);
				}

				int sourcePort = receivePacket.getPort();
				BattleBarn.addProcessorTask(new ProcessorThread(packetData, ipAddress, sourcePort));
				BattleBarn.packetsIn++;
			} catch (SocketException ex) {
				Logger.getLogger(GameListener.class.getName()).log(Level.SEVERE, null, ex);
			} catch (IOException ex) {
				Logger.getLogger(GameListener.class.getName()).log(Level.SEVERE, null, ex);
			}
		}
	}
}
